package demo2;

public class T {

    private int count = 10;

    public void m() {
        synchronized (this) {//任何线程要执行下面的代码，必须先拿到this的锁
            count--;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("%s count = %d%n", Thread.currentThread().getName(), count);
        }
    }

    //m()等同于下面的m2()
    public synchronized void m2() {  //等同于在方法的代码执行时要synchronized(this)
        count--;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%s count = %d%n", Thread.currentThread().getName(), count);
    }


    public static void main(String[] args) {
        final T t = new T();
        Thread thread1 = new Thread(t::m);
        Thread thread2 = new Thread(t::m);
        thread1.start();
        thread2.start();
    }
}
